(ns fx-clj.controls.remote-table
  (:require [fx-clj.core :as fx]
            [freactive.core :as f]
            [clojure.core.async :refer [chan <! go-loop]]
            [org.httpkit.client :as http-kit]
            [cheshire.core :as json])
  (:import (javafx.application Platform)))

(def url "http://git.oschina.net/ellipse/mistlibs.fx-clj/raw/master/sample.json")

(def state (f/atom {:loading? false
                    :data     []}))

(add-watch state :kkk
  (fn [_ _ _ n]
    (prn "-->" n)))

(def loading? (f/cursor state :loading?))
(def table-data (f/cursor state :data))

(defn load-data []
  (reset! loading? true)
  (http-kit/get url {}
                (fn [{:keys [status headers body error] :as resp}]
                  (let [json (json/parse-string body true)]
                    (reset! table-data (:customers json)))
                  (reset! loading? false))))

(let []
  (defn create-view []
    (let [ch (chan)
          ch2 (chan)
          table (fx/table-view
                  {:columns [(fx/table-column {:text               :id
                                               :cell-value-factory :id})
                             (fx/table-column {:text               "姓名"
                                               :cell-value-factory :name})
                             (fx/table-column {:text               "年龄"
                                               :cell-value-factory :age})
                             (fx/table-column {:text               "国籍"
                                               :cell-value-factory :country})]
                   :items   table-data})
          button (fx/button {:on-action ch} "Refresh")
          button2 (fx/button {:on-action ch2} "Print")
          mask (fx/stack-pane {:visible loading?}
                              (fx/progress-indicator))
          view (fx/stack-pane
                 (fx/v-box table button button2)
                 mask)]
      (go-loop []
        (<! ch2)
        (let [items (. table getItems)
              comparator (. table getComparator)]
          (println items)
          (println comparator))
        (recur))
      (go-loop []
        (<! ch)
        (load-data)
        (recur))
      view)))

(Platform/setImplicitExit true)
(fx/sandbox #'create-view)